package ltd.dujiabao.activemq.jms;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

import javax.jms.*;

/**
 * @author : DuJiabao
 * @Project : active-mq
 * @Time : 2021/5/4 23:07
 * @Desc :
 */
public class TopicPersistenceProducer {
  private static final String ACTIVEMQ_URL = "tcp://192.168.233.134:61616";  // 服务器端口号，地址
  private static final String DESTINATION_NAME = "topic01";  // 目的地名称


  @Test
  public void test() throws Exception {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
    Connection connection = activeMQConnectionFactory.createConnection();
    connection.start();   // 开始连接
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(topic);

    // 以往都是直接开启连接，这次要拿了producer，设置为持久化，才能开启连接？
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);     // 设置为持久化的。重点！！！
    // connection.start();   // 开始连接

    // 发送消息
    for (int i = 0; i < 10; i++) {
      TextMessage message = session.createTextMessage("message:" + i);// 创建一个要发送的消息对象，该对象存储的是字符串
      producer.send(message);// 生产者负责将消息对象发送出去
    }
    System.out.println("发送消息完毕");

    producer.close();
    session.close();
    connection.close();
  }
}
